#include "http_scheme_factory.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
#include <Windows.h>

#include "internal/cef_string_types.h"
#include "capi/cef_scheme_capi.h"
#include "capi/cef_stream_capi.h"

#include "tools/file_utils.h"
#include "stream_resource_handler.h"
#include "tools/log_util.h"

// 全局对象，cef关闭前清理
cef_scheme_handler_factory_t* g_http_scheme_factory = NULL;

struct _cef_resource_handler_t *CEF_CALLBACK create(
    struct _cef_scheme_handler_factory_t *self,
    struct _cef_browser_t *browser,
    struct _cef_frame_t *frame,
    const cef_string_t *scheme_name,
    struct _cef_request_t *request)
{
    LOG_DEBUG("start----------");
    // 获取请求的URL
    cef_string_userfree_t url = request->get_url(request);
    cef_string_utf8_t url_utf8 = {0};
    cef_string_utf16_to_utf8(url->str, url->length, &url_utf8);

    // 定义url 前缀并处理
    char *prefix = "http://local_file/";
    if (strncmp(url_utf8.str, prefix, strlen(prefix)) != 0)
    {
        cef_string_userfree_free(url);
        return NULL;
    }
    // 提取路径部分
    char *path = url_utf8.str + strlen(prefix); // 指针偏移， 截去 前缀
    char *query = strchr(path, '?');
    if (query != NULL)
    {
        *query = '\0'; // 截断字符串， 删除查询参数
    }

    // 转换路径为Windows路径
    char *winPath = convertLinuxPathToWindows(path);
    if (winPath == NULL)
    {
        LOG_ERROR("path convert error----------");
        return NULL;
    }

    // 将 winPath 转换为宽字符字符串
    wchar_t winPath_wide[MAX_PATH * 2] = {0};
    size_t converted_chars = mbstowcs(winPath_wide, winPath, MAX_PATH * 2);
    if (converted_chars == (size_t)-1)
    {
        LOG_ERROR("mbstowcs conversion failed----------");
        free(winPath); // 释放 winPath
        return NULL;
    }

    // 获取模块路径
    wchar_t exe_path[MAX_PATH] = {0};
    GetModuleFileNameW(NULL, exe_path, MAX_PATH);
    wchar_t *last_slash = wcsrchr(exe_path, L'\\');
    if (last_slash)
    {
        *last_slash = L'\0';
    }

    // 构建目标路径
    wchar_t target_path[MAX_PATH * 2] = {0};
    swprintf(target_path, MAX_PATH * 2, L"%s\\%s", exe_path, winPath_wide);

    if (_waccess(target_path, 0) == -1)
    {
        LOG_ERROR("file not found: %s", wide_to_utf8(target_path));
    }

    // 获取MIME类型
    const wchar_t *ext = wcsrchr(target_path, L'.');
    cef_string_t mime_type = {0};
    if (ext && wcscmp(ext, L".html") == 0)
    {
        cef_string_from_ascii("text/html", 9, &mime_type);
    }
    else if (ext && wcscmp(ext, L".css"))
    {
        cef_string_from_ascii("text/css", 8, &mime_type);
    }
    else if (ext && wcscmp(ext, L".js"))
    {
        cef_string_from_ascii("application/javascript", 22, &mime_type);
    }
    else
    {
        cef_string_from_ascii("*", 1, &mime_type);
    }
    
    // 创建文件读取流
    cef_string_t wpath = {0};
    cef_string_wide_to_utf16(target_path, wcslen(target_path), &wpath);
    cef_stream_reader_t *reader = cef_stream_reader_create_for_file(&wpath);
    cef_string_clear(&wpath);
    
    // 创建资源处理器
    cef_string_t status_text = {0};
    cef_string_from_ascii("OK", 2, &status_text);
    cef_string_multimap_t header_map = cef_string_multimap_alloc();
    cef_resource_handler_t *handler = create_stream_resource_handler(200, &status_text, &mime_type, header_map, reader);
    
    // 清理资源
    cef_string_userfree_free(url);
    cef_string_utf8_clear(&url_utf8);
    cef_string_clear(&mime_type);
    // cef_string_multimap_free(header_map);
    LOG_DEBUG("create", "exec end----------");
    return handler;
}

// 初始化 http_scheme_factory_ref_t
cef_scheme_handler_factory_t* create_http_scheme_factory_t()
{
    cef_scheme_handler_factory_t *factory =(cef_scheme_handler_factory_t *)calloc(1, sizeof(cef_scheme_handler_factory_t));
    factory->base.size = sizeof(cef_scheme_handler_factory_t);
    factory->create = create;

    return factory;
}